#include "test-item-camera-module.h"
#include "test-module-external-interface.h"

#define WIDTH 640
#define HEIGHT 480

extern testModuleExternalInterface_t testModuleExternalInterface;

bool test_item_camera_module_work_falg;

TestItemCameraModule::TestItemCameraModule(/* args */)
{
}

TestItemCameraModule::~TestItemCameraModule()
{
}

void *camera_module_work_pthread(void *arg)
{
    TestModuleFrameFormat *argFrameFormat = (TestModuleFrameFormat *)arg;
    uint8_t send_data[2];
    send_data[0] = TEST_CAMERA_MODULE;

    // // 创建变量
    // taiic_rkisp_s main_ctx;
    // memset(&main_ctx, 0, sizeof(main_ctx));
    // // 1、打开摄像头
    // GlobalInterface.init_rkisp_ctx_f(&main_ctx);
    
    // GlobalInterface.init_rkisp_routine_f(&main_ctx);

    // GlobalInterface.init_device_f(&main_ctx);
    // printf("===This is line %d in the file===\n",__LINE__);

    // GlobalInterface.start_capturing_f(&main_ctx);
    // printf("%s:-------- stream on mipi tx/rx -------------\n", GlobalInterface.get_sensor_name_f(&main_ctx));

    // while (main_ctx.frame_count == -1 && main_ctx.outputCnt > 0) 
    // {
    //     GlobalInterface.read_frame_f(&main_ctx);
    // }

    // GlobalInterface.stop_capturing_f(&main_ctx);

    // GlobalInterface.deinit_rkisp_f(&main_ctx);

    // GlobalInterface.uninit_device_f(&main_ctx);

    // GlobalInterface.close_device_f(&main_ctx);
    while (test_item_camera_module_work_falg)
    {
        sleep(1);
    }
    
    
    send_data[1] = TEST_STOPED;
    argFrameFormat->framePackageFunction(send_data, sizeof(send_data));
    printf("相机模组测试线程退出！\n");
    return nullptr;
}

int TestItemCameraModule::recv_command_data(void *data, uint16_t length)
{
    if((NULL == data) || (length < 2))
    {
        printf("传入参数错误！\n");
        return -1;
    }

    int ret;
    uint8_t recvBuffer[length] = {0};
    uint8_t sendBuffer[2] = {0};
    sendBuffer[0] = TEST_CAMERA_MODULE;

    memcpy(recvBuffer, data, length);

    if(recvBuffer[1] == TEST_START)//开始
    {
        test_item_camera_module_work_falg = true;
        ret = pthread_create(&work_pthread, NULL, camera_module_work_pthread, (void *)&frameOperate);
        if(ret == -1)
        {
            printf("相机模组测试，创建线程失败！\n");
            return ret;
        }
        sendBuffer[1] = TEST_STARTED;
        frameOperate.framePackageFunction(sendBuffer, sizeof(sendBuffer));
    }else if(recvBuffer[1] == TEST_STOP)//停止
    {
        test_item_camera_module_work_falg = false;
        printf("相机模组测试结束！\n");
    }else
    {
        printf("数据错误：%x , %x \n", recvBuffer[0], recvBuffer[1]);
    }

    return 0;
}
